// wrap the method in the init-middleware here
import { JsonqlError } from 'jsonql-errors'
import { isContract, getDebug } from '../utils'
const debug = getDebug('process-contract')

/**
 * Create the start of chain
 * @param {object} opts configuration
 * @return {object} promise resolve the contract if found
 */
const getFromOpts = opts => {
  return Promise.resolve(
    isContract(opts.contract)
  )
}

/**
 * @param {object} ctx koa context
 * @param {object} opts configuration
 * @return {object} promise to resolve the contract
 */
export default async function processContract(ctx, opts) {
  // const { setter, getter } = ctx.state.jsonql;
  return getFromOpts(opts)
    .then(c => c || false)
    // .then(c => !c ? getter('contract') : c)
    .then(c => {
      if (!c) {
        if (!ctx.state.jsonql.contract && opts.initContract && opts.initContract.then) {
          debug('calling the initContract to get the contract')
          return opts.initContract.then(c => {
            // disable the cache for the time being
            // setter('contract', c)
            return c;
          })
        }
        throw new JsonqlError('Unable to get the contract!')
      }
      return c;
    })
}
